﻿Imports WRDB.Project
Imports System.Web.Configuration

Public Class Configure
    Inherits System.Web.UI.Page

    Private ThisProjectSettings As New clsProjectSettings
    Private Shared PrevPage As String = ""
    Private ExternalConnection As String = ""
    Private ImageFile As String = ""

    Protected Overrides Sub InitializeCulture()
        With ProjectSettings
            System.Threading.Thread.CurrentThread.CurrentUICulture = .Language
            System.Threading.Thread.CurrentThread.CurrentCulture = .Language
        End With

        MyBase.InitializeCulture()
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        'set language-specific variables
        ExternalConnection = CStr(HttpContext.GetGlobalResourceObject("WRDB", "ExternalConnection"))

        If Not IsPostBack Then
            'save calling page
            If Request.UrlReferrer IsNot Nothing Then PrevPage = Request.UrlReferrer.ToString

            'get list of projects and users from web.config
            Dim dictUsers As New Dictionary(Of String, String)
            For Each k As String In ConfigurationManager.AppSettings.AllKeys
                If Not dictUsers.ContainsKey(k) Then dictUsers.Add(k, ConfigurationManager.AppSettings(k))
            Next

            'initialize list of projects by retrieving from default location according to WRDB installation and then sorting the list
            cboProjects.Items.Clear()
            Dim lstProj As New List(Of String)
            For Each kv In WRDB.Project.clsConnections.GetProjectList
                'if web.config file has a user list for the project and current user is not among them, do not display project
                If Not dictUsers.ContainsKey(kv.Key) OrElse dictUsers(kv.Key).ToUpper.Replace(" ", "").Split(",").Contains(GetLoginName.ToUpper) Then
                    lstProj.Add(kv.Key & " - " & kv.Value)
                End If
            Next
            lstProj.Sort()
            For Each s As String In lstProj
                cboProjects.Items.Add(s)
            Next

            Dim lstExt As New List(Of String)
            For Each s As String In WRDB.Project.clsConnections.GetConnectionNames
                lstExt.Add(s & " - " & ExternalConnection)
            Next
            lstExt.Sort()
            For Each s As String In lstExt
                cboProjects.Items.Add(s)
            Next

            'set project and table to last one selected

            With ThisProjectSettings
                If .Load Then
                    For i As Integer = 0 To cboProjects.Items.Count - 1
                        If GetName(cboProjects.Items(i).Text) = .ProjectName.Replace("_", " ") Then
                            cboProjects.SelectedIndex = i
                            Exit For
                        End If
                    Next
                    FillTableList()
                    For i As Integer = 0 To lstTables.Items.Count - 1
                        If GetName(lstTables.Items(i).Text) = .TableName.Replace("_", " ") Then
                            lstTables.SelectedIndex = i
                            Exit For
                        End If
                    Next
                    txtTimeout.Text = .Timeout
                    txtMaxRows.Text = .MaxRows
                Else
                    If cboProjects.Items.Count > 0 Then
                        cboProjects.SelectedIndex = 0
                        FillTableList()
                    End If
                    txtTimeout.Text = 30
                    txtMaxRows.Text = 100000
                End If
            End With

            'fill project users grid which is only visible if Advanced button is clicked
            'comma separated lists of allowed users for each project are stored in web.config file

            Dim dtProjectUsers As New DataTable

            With dtProjectUsers
                .Columns.Add(GetGlobalResourceObject("WRDB", "ProjectName"), GetType(String))
                .Columns(0).ReadOnly = True
                .Columns.Add(GetGlobalResourceObject("WRDB", "PermittedUsers"), GetType(String))
                Dim projects As New List(Of String)
                projects.AddRange(WRDB.Project.clsConnections.GetProjectList.Keys)
                projects.Sort()
                For Each s As String In projects
                    .Rows.Add(s, ConfigurationManager.AppSettings(s))
                Next
            End With
            gvProjectUsers.DataSource = dtProjectUsers
            gvProjectUsers.DataBind()

            Session("dtProjectUsers") = dtProjectUsers
        End If
    End Sub

    Private Sub lstProjects_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboProjects.SelectedIndexChanged
        'if change project, clear out prior settings
        With ProjectSettings
            .LastQuery.Clear()
            .GraphPCode = ""
            .GraphStation = ""
        End With
        FillTableList()
    End Sub

    Private Sub FillTableList()
        'if selected project changed, set project and then refresh list of working and Master tables
        'note: Ivan wants all table names with underscores to appear with spaces instead (then must convert back when select)
        'note: Ivan wants tables containing the string 'Analisis' to be hidden
        If cboProjects.SelectedIndex = -1 Then Exit Sub
        Dim IsExternal As Boolean = (GetDesc(cboProjects.Text) = ExternalConnection)
        Dim lstTbl As New List(Of String)
        lstTables.Items.Clear()
        lblError.Visible = False

        If IsExternal Then
            For Each s In clsConnections.GetMappingTables(GetName(cboProjects.Text))
                lstTbl.Add(s.replace("_", " "))
            Next
        Else
            Dim ThisProject As WRDB.Project.clsProject = Nothing
            Try
                ThisProject = New WRDB.Project.clsProject(GetName(cboProjects.Text))
            Catch ex As Exception
                ThisProject = Nothing
            End Try
            With ThisProject
                If ThisProject Is Nothing Then
                    lblError.Text = String.Format(GetGlobalResourceObject("WRDB", "CannotConnect"), "Unknown", "Unknown", False)
                    lblError.Visible = True
                    Exit Sub
                ElseIf Not .DB.TestConnection Then
                    lblError.Text = String.Format(GetGlobalResourceObject("WRDB", "CannotConnect"), .DB.DataSource, .DB.DatabaseName, .DB.UserName = "")
                    lblError.Visible = True
                    Exit Sub
                End If
            End With

            imgProject.ImageUrl = ProjectImageURL(ThisProject)
            imgProject.Visible = imgProject.ImageUrl <> ""

            'get tracking table so can get working table descriptions
            Dim dtTracking As DataTable = Nothing
            ThisProject.DB.AddTable(dtTracking, "SELECT * FROM TRACKING")
            dtTracking.CaseSensitive = False

            Dim lstMaster As List(Of String) = ThisProject.GetTableList(clsProject.enumTableTypes.Master)

            If lstMaster.Count > 0 Then lstTables.Items.Add(String.Format("{0} - ({1})", lstMaster(0), GetGlobalResourceObject("WRDB", "MasterTable")))

            For Each s In ThisProject.GetTableList(clsProject.enumTableTypes.Working)
                If Not s.Contains("Analisis") Then 'Ivan doesn't want to see these type of working tables
                    Dim dr() As DataRow = dtTracking.Select(String.Format("Temp_DB_Name = '{0}'", s))
                    If dr.Length > 0 AndAlso Not IsDBNull(dr(0)("Description")) Then s &= " - " & dr(0)("Description")
                    lstTbl.Add(s.Replace("_", " "))
                End If
            Next
        End If
        lstTbl.Sort()

        For Each s As String In lstTbl
            lstTables.Items.Add(s)
        Next

        If lstTables.Items.Count > 0 Then lstTables.SelectedIndex = 0
    End Sub

    Private Function GetName(Entry As String) As String
        Return StringSplit(Entry, " - ")(0)
    End Function

    Private Function GetDesc(Entry As String) As String
        If Entry.Contains(" - ") Then Return StringSplit(Entry, " - ")(1) Else Return ""
    End Function

    Private Sub gvProjectUsers_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles gvProjectUsers.RowCancelingEdit

        gvProjectUsers.EditIndex = -1
        gvProjectUsers.DataSource = Session("dtProjectUsers")
        gvProjectUsers.DataBind()
        ShowProjectUsersDialog()

    End Sub

    Private Sub gvProjectUsers_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles gvProjectUsers.RowDataBound

        If e.Row.RowType = DataControlRowType.DataRow Or
            e.Row.RowType = DataControlRowType.Header Then
            e.Row.Cells(0).Width = New Unit(1, UnitType.Pixel)
            e.Row.Cells(1).Width = New Unit(1, UnitType.Pixel)
            e.Row.Cells(1).Wrap = False
            If e.Row.RowState = DataControlRowState.Edit Then
                With CType(e.Row.Cells(1).Controls(0), TextBox)
                    .Enabled = False
                    .ReadOnly = True
                End With
                With CType(e.Row.Cells(2).Controls(0), TextBox)
                    .Width = New Unit(100, UnitType.Percentage)
                    .Wrap = True
                End With
            End If
        End If

    End Sub

    Private Sub gvProjectUsers_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles gvProjectUsers.RowEditing

        gvProjectUsers.EditIndex = e.NewEditIndex
        gvProjectUsers.DataSource = Session("dtProjectUsers")
        gvProjectUsers.DataBind()
        ShowProjectUsersDialog()

    End Sub

    Private Sub gvProjectUsers_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles gvProjectUsers.RowUpdating

        'Retrieve the table from the session object.
        Dim dtProjectUsers As DataTable = Session("dtProjectUsers")

        'Update the values.
        Dim row = gvProjectUsers.Rows(e.RowIndex)
        dtProjectUsers.Rows(row.DataItemIndex)(1) = (CType((row.Cells(2).Controls(0)), TextBox)).Text

        'Reset the edit index.
        gvProjectUsers.EditIndex = -1

        'Bind data to the GridView control.
        gvProjectUsers.DataSource = dtProjectUsers
        gvProjectUsers.DataBind()
        ShowProjectUsersDialog()

    End Sub

    Private Sub btnAdvanced_Click(sender As Object, e As EventArgs) Handles btnAdvanced.Click
        ShowDialog(UpdatePanel1, pnlDialogPassword, GetGlobalResourceObject("WRDB", "AdvancedPswd"), 500)
    End Sub

    Private Sub btnPasswordOK_Click(sender As Object, e As EventArgs) Handles btnPasswordOK.Click
        Dim webconfig As System.Configuration.Configuration = WebConfigurationManager.OpenWebConfiguration("~")
        Dim pswd As String = ""
        If webconfig.AppSettings.Settings.AllKeys.Contains("AdministrativePassword") Then pswd = webconfig.AppSettings.Settings("AdministrativePassword").Value
        If pswd = "" Then 'it didn't already exist so set default one
            pswd = "pswd"
            webconfig.AppSettings.Settings.Add("AdministrativePassword", pswd)
            webconfig.Save()
            Response.Redirect("Configure.aspx") 'when web.config is changed website restarts; restart this page too
        End If
        If txtPassword.Text = pswd Then
            ShowProjectUsersDialog()
        End If
    End Sub

    Private Sub ShowProjectUsersDialog()
        ShowDialog(UpdatePanel1, pnlDialogProjectUsers, GetGlobalResourceObject("WRDB", "AdvancedConfig"), 800, True)
    End Sub

    Private Sub btnUsersCancel_Click(sender As Object, e As EventArgs) Handles btnUsersCancel.Click
        gvProjectUsers.EditIndex = -1
    End Sub

    Private Sub btnUsersOK_Click(sender As Object, e As EventArgs) Handles btnUsersOK.Click
        If gvProjectUsers.EditIndex <> -1 Then gvProjectUsers.UpdateRow(gvProjectUsers.EditIndex, False)
        gvProjectUsers.EditIndex = -1
        'save to appsettings
        Dim webconfig As System.Configuration.Configuration = WebConfigurationManager.OpenWebConfiguration("~")
        For r As Integer = 0 To gvProjectUsers.Rows.Count - 1
            With gvProjectUsers.Rows(r)
                Dim proj As String = .Cells(1).Text
                Dim usrs As String = .Cells(2).Text
                If usrs = "&nbsp;" Then usrs = "" 'empty cells look like this for some reason
                webconfig.AppSettings.Settings.Remove(proj)
                If usrs.Trim <> "" Then webconfig.AppSettings.Settings.Add(proj, usrs.Trim)
            End With
        Next
        webconfig.Save()
        Response.Redirect("Default.aspx") 'when web.config is changed website restarts; restart this page too
    End Sub

    Protected Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
        'if invalid data entered, loop
        If cboProjects.SelectedIndex = -1 Or lstTables.SelectedIndex = -1 Or Not IsNumeric(txtTimeout.Text) Or Not IsNumeric(txtMaxRows.Text) Then
            HttpContext.Current.Response.Redirect("Configure.aspx")
            Exit Sub
        End If

        'save new selections as cookies then display the select data form
        With ProjectSettings
            .ProjectName = GetName(cboProjects.Text)
            .TableName = GetName(lstTables.Text).Replace(" ", "_")
            If IsNumeric(txtTimeout.Text) Then .Timeout = txtTimeout.Text
            If IsNumeric(txtMaxRows.Text) Then .MaxRows = txtMaxRows.Text
            .Save()
        End With
        ResetProject()
        Response.Redirect("SelectData.aspx")
    End Sub

    Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
        Response.Redirect(PrevPage)
    End Sub

    ''' <summary>
    ''' This PageMethod allows a resource value to be passed to the page so JavaScript can display message in correct language
    ''' </summary>
    <System.Web.Services.WebMethod()>
    Public Shared Function GetResource(key As String) As String
        Dim res As String = HttpContext.GetGlobalResourceObject("WRDB", key, ProjectSettings.Language)
        If String.IsNullOrEmpty(res) Then Throw New ApplicationException("Resource was not found: " & key) Else Return res
    End Function

End Class